package com.zzc.zzcapi.controller;

import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.keleclientsdk.client.KeleApiClient;
import com.zzc.zzcapi.annotation.AuthCheck;
import com.zzc.zzcapi.common.BaseResponse;
import com.zzc.zzcapi.common.DeleteRequest;
import com.zzc.zzcapi.common.ErrorCode;
import com.zzc.zzcapi.common.ResultUtils;
import com.zzc.zzcapi.constant.UserConstant;
import com.zzc.zzcapi.exception.BusinessException;
import com.zzc.zzcapi.exception.ThrowUtils;
import com.zzc.zzcapi.model.dto.interfaceInfo.InterfaceInfoAddRequest;
import com.zzc.zzcapi.model.dto.interfaceInfo.InterfaceInfoInvokeRequest;
import com.zzc.zzcapi.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.zzc.zzcapi.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.zzc.zzcapi.model.entity.InterfaceInfo;
import com.zzc.zzcapi.model.entity.User;
import com.zzc.zzcapi.model.vo.InterfaceInfoVO;
import com.zzc.zzcapi.service.InterfaceInfoService;
import com.zzc.zzcapi.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 帖子接口
 *
 * @author 张昭冲
 * 
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;
    @Resource
    private UserService userService;
    @Resource
    private KeleApiClient keleApiClient;

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);

        // 校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        interfaceInfo.setUserid(loginUser.getId());

        boolean result = interfaceInfoService.save(interfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newInterfaceInfoId = interfaceInfo.getId();
        return ResultUtils.success(newInterfaceInfoId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserid().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param interfaceInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest,
                                                     HttpServletRequest request) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);

        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        User user = userService.getLoginUser(request);
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(oldInterfaceInfo == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅管理员可修改
        if(!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<InterfaceInfoVO> getInterfaceInfoVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(interfaceInfoService.getInterfaceInfoVO(interfaceInfo, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param interfaceInfoQueryRequest
     * @return
     */
    @GetMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size),
                interfaceInfoService.getQueryWrapper(interfaceInfoQueryRequest));
        return ResultUtils.success(interfaceInfoPage);
    }

    /**
     * 接口发布上线
     * @param interfaceInfo
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/online")
    public BaseResponse InterfaceOnline(@RequestBody InterfaceInfo interfaceInfo) {
        if(interfaceInfo == null || interfaceInfo.getId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMessage());
        }

        InterfaceInfo info = interfaceInfoService.getById(interfaceInfo);
        // todo 这里是请求写死的
        // 服务端返回状态码为200表示调用成功。
        HttpResponse httpResponse = keleApiClient.hello("张三");
        if(httpResponse == null || httpResponse.getStatus() != 200) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR.getCode(), ErrorCode.SYSTEM_ERROR.getMessage());
        }
        // 请求成功，修改该status为1
        info.setStatus(1);
        interfaceInfoService.updateById(info);
        return ResultUtils.success(null);
    }

    /**
     * 接口下线
     * @param interfaceInfo
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/offline")
    public BaseResponse Interfaceoffline(@RequestBody InterfaceInfo interfaceInfo) {
        if(interfaceInfo == null || interfaceInfo.getId() < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMessage());
        }
        InterfaceInfo info = interfaceInfoService.getById(interfaceInfo);
        // 请求成功，修改该status为1
        info.setStatus(0);
        interfaceInfoService.updateById(info);
        return ResultUtils.success(null);
    }

    /**
     * 根据接口id返回接口信息
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfo> getApi(long id) {
        if(id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo info = interfaceInfoService.getById(id);
        return ResultUtils.success(info);
    }

    /**
     *
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> interfaceInvoke(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest,
                                                HttpServletRequest request) {
        if(interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取前端请求参数
        String userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        // 获取当前用户信息
        User loginUser = userService.getLoginUser(request);
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        // todo 固定地址发起请求
        KeleApiClient temp_keleApiClient = new KeleApiClient(accessKey, secretKey);
        HttpResponse response = response = temp_keleApiClient.hello(interfaceInfoInvokeRequest.getUserRequestParams());

        if(response.getStatus() == 200) { // 状态码为200，返回响应体内容
            return ResultUtils.success(response.body());
        }
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "接口异常，或请更新调用次数");
    }
}
